from django.template import RequestContext
from django.shortcuts import render_to_response
from django import forms
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

class RegisterManipulator(forms.Manipulator):
	def __init__(self):
		self.fields = \
				(
					forms.TextField(field_name="username",is_required = True,maxlength=32),
					forms.EmailField(field_name="email",is_required = True,maxlength=32),
					forms.TextField(field_name="first_name",is_required = True,maxlength=32),
					forms.TextField(field_name="last_name",is_required = True,maxlength=32),
					forms.PasswordField(field_name="password",is_required = True,maxlength=32),
					forms.PasswordField(field_name="passwordc",is_required = True,maxlength=32),
				)

def register(request):
	c = RequestContext(request)

	manipulator = RegisterManipulator()

	if request.POST:
		data = request.POST.copy()
		errors = manipulator.get_validation_errors(data)
		if not errors:
			if data['passwordc'] != data['password']:
				errors = {'passwordc':_("Passwords don't match")}
				data['password'] = data['passwordc'] = ''
			else:
				user = User.objects.create_user(data['username'],data['email'],data['password'])
				user.first_name,user.last_name = data['first_name'],data['last_name']
				user.save()
				return HttpResponseRedirect(reverse("django.contrib.auth.views.login",None,(),{}))
	else:
		data = errors = {}
	c['form'] = forms.FormWrapper(manipulator,data,errors)
	return render_to_response('registration/register.xhtml',c)

def welcome(request):
	c = RequestContext(request)
	return render_to_response('registration/welcome.xhtml',c)
